// pages/balance/index.js
// 后端配置
import {
  BasicUrl,
  request
} from "../../api/config.js"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    BasicUrl: '',
    // 商品小计
    total_price: 0,
    // 商品总数
    total_num: 0,
    // 打开自取时间选择
    showTime: false,
    // 左侧选中项的索引	
    mainActiveIndex: 0,
    // 右侧选中项的 id，支持传入数组
    activeId: 1,
    // 下单门店信息
    store_info: {},
    // 下单的商品明细
    goods_info: [],
    // 选择自取时间信息
    items: [],
    time: '',
    day: '',
    // 备注
    showRemarks: false,
    checkPhone: false,
    form: {
      // 预留手机号
      phone: '',
      // 外卖手机号
      deliveryPhone:'',
      // 取餐方式 1:店内，2：打包
      meal_pickup_type: 1,
      // 自取时间
      selfPickupTime: '',
      // 备注
      remarks: '',
      // 订单类型 自提：1  外卖：2
      order_type: 1,
      // 外卖手机号
      contacts: '',
      tag: '',
      address: '',
      detailed_address: '',
      sex: "",
    },
    remarks: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkForm()
    this.get_store()
    this.get_goods_info()
    this.setData({
      BasicUrl: BasicUrl
    })
    this.get_selfPickupTime_info()
    this.getAdderss()
  },
  // 置空form
  checkForm(){
    // 进来全部输入信息置空
    let form = {
      // 预留电话
      phone: '',
       // 外卖手机号
       deliveryPhone:'',
      // 取餐方式 1:店内，2：打包
      meal_pickup_type: 1,
      // 自取时间
      selfPickupTime: '',
      // 备注
      remarks: '',
      // 订单类型 自提：1  外卖：2
      order_type: 1,
      contacts: '',
      tag: '',
      address: '',
      detailed_address: '',
      sex: "",
    }
    this.setData({
      form: form
    })
  },
  // 获取地址
  getAdderss() {
    let {
      address,
      contacts,
      detailed_address,
      phone,
      sex,
      tag
    } = wx.getStorageSync('delivery_address') ? JSON.parse(wx.getStorageSync('delivery_address')) : {}
    if (address) {
      this.setData({
        'form.contacts': contacts,
        'form.tag': tag,
        'form.address': address,
        'form.detailed_address': detailed_address,
        'form.deliveryPhone': phone,
        'form.sex': sex,
      })
      console.log(this.data.form);
    }
  },
  inputRemarks(event) {
    this.setData({
      remarks: event.detail
    })
  },
  // 立即支付
  async payment() {
    console.log(this.data.form);
    console.log(this.data.goods_info);
    let user_id = JSON.parse(wx.getStorageSync('user_info')).user_id
    let query = {
      ...this.data.form,
      goods_detail: JSON.stringify(this.data.goods_info),
      user_id: user_id,
      store_info: wx.getStorageSync('store_info'),
      order_total: this.data.total_price,
      order_num: this.data.total_num
    }
    // 订单类型为自提的
    if (this.data.form.order_type == 1) {
      if (this.data.checkPhone || this.data.form.phone.length == 0) {
        return wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
      }
    } else {
      if (!this.data.form.address) {
        return wx.showToast({
          title: '请选择配送地址',
          icon: 'none'
        })
      }
    }
    wx.showLoading({
      title: '正在下单...',
    })
    await request("/api/order/create_order", 'post', query, true).then(({
      data
    }) => {
      console.log(data);
      if (data.code == 200) {
        wx.showToast({
          title: '下单成功',
          icon: 'success'
        })
        wx.setStorageSync('createOrder', false)
        // 删除缓存购物车的商品
        wx.removeStorageSync('card_data')
        setTimeout(()=>{
          // 模拟支付
        this.simulationPay(data.data.order_id, query.user_id)
        },1000)
      } else {
        wx.showToast({
          title: '下单失败',
          icon: 'error'
        })
      }
    })
    wx.hideLoading()
  },
  // 模拟支付
  simulationPay(order_id, user_id) {
      wx.showModal({
        title: '模拟支付',
        content: '确认支付？',
        complete: (res) => {
          // 点击了取消
          if (res.cancel) {
            wx.switchTab({
              url: '/pages/order/index',
            })
            console.log('cancel', res.cancel);
          }
          // 点击了确认
          if (res.confirm) {
            request('/api/order/pay_order', 'post', {
              order_id,
              user_id
            }, true).then(({
              data
            }) => {
              console.log(data);
              if (data.code == 200) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success'
                })
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/order/index',
                  })
                }, 500)
              } else {
                wx.showToast({
                  title: '支付失败',
                  icon: 'error'
                })
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/order/index',
                  })
                }, 500)
              }
            })

          }
        }
      })
  },
  selectAddress() {
    wx.navigateTo({
      url: '/pages/myAddress/index',
    })
  },
  ChangeRadio() {
    wx.showToast({
      title: '必须勾选项',
      icon: 'none'
    })
  },
  // 打开备注弹窗
  showRemarksInput() {
    if (this.data.form.remarks) {
      this.setData({
        remarks: this.data.form.remarks
      })
    }
    this.setData({
      showRemarks: true
    })
  },
  // 保存备注
  submitRemarks() {
    console.log(this.data.remarks);
    if (this.data.remarks) {
      this.setData({
        'form.remarks': this.data.remarks
      })
    }
    this.setData({
      showRemarks: false
    })
  },
  onClose() {
    this.setData({
      showRemarks: false
    })
  },
  // 切换取餐方式
  changeMealsType(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      'form.meal_pickup_type': type
    })
  },
  // 选择自取时间
  selectSelfPickupTime(e) {
    this.setData({
      showTime: true
    })
  },
  closeTimeSheet() {
    this.setData({
      showTime: false
    })
  },
  // 点击自取时间
  click_time(event) {
    this.setData({
      showTime: false,
    })
  },
  // 获取默认自取时间
  get_selfPickupTime_info() {
    let now = new Date();
    let hours = now.getHours();
    let minutes = now.getMinutes();
    let dayOfWeek = now.getDay();

    let time = hours + ":" + minutes;
    let day = "";

    // 使用一个数组映射来获取星期几的名称  
    const days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    if (dayOfWeek < 7 && dayOfWeek > 0) {
      day = days[dayOfWeek];
    } else {
      day = "周日"; // 或者你可以设置默认为 "Invalid Day" 如果日期是错误的或者不合法  
    }
    console.log("Current Time: " + time); // 输出当前时间，例如 "12:30"  
    console.log("Day of the Week: " + day); // 输出当前星期几，例如 "Monday"

    // 创建选择时间数组
    let items = [{
      text: '今天(' + day + ')',
      children: [{
        id: 1,
        text: '现在下单' + time
      }]
    }]
    this.setData({
      items: items,
      time,
      day,
      'form.selfPickupTime': day + time
    })
  },
  // 自动填写
  autoFill() {
    let phone = JSON.parse(wx.getStorageSync('user_info')).phone
    console.log(phone);
    if (phone > 0) {
      this.setData({
        'form.phone': phone,
        checkPhone: false
      })
    } else {
      wx.showToast({
        title: '请完善手机号',
        icon: 'error'
      })
    }
  },
  // 输入手机号
  ChangePhone(e) {
    this.setData({
      'form.phone': e.detail
    })
  },
  checkPhone(e) {
    console.log(e.detail);
    let val = e.detail.value
    if (!Number(val) || val.length < 11) {
      this.setData({
        checkPhone: true
      })
    } else {
      this.setData({
        checkPhone: false
      })
    }
    console.log(this.data.checkPhone);
  },
  // 获取购物车下单的商品
  get_goods_info() {
    let card_data = wx.getStorageSync('card_data')
    console.log(card_data);
    let total_price = 0
    let total_num = 0
    card_data.forEach(item => {
      total_price += (item.goods_price - item.goods_preferential) * item.num
      total_num += item.num
    })
    this.setData({
      goods_info: card_data,
      total_price: total_price,
      total_num: total_num
    })
  },
  // 获取当前下单门店
  get_store() {
    let stroe_info = JSON.parse(wx.getStorageSync('store_info'))
    console.log(stroe_info);
    this.setData({
      store_info: stroe_info
    })
  },
  // 切换订单类型
  changeType(e) {
    console.log(e.currentTarget.dataset.type);
    let type = e.currentTarget.dataset.type
    this.setData({
      'form.order_type': type
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAdderss()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

})